<template>
	<view class="container user-mysponsor">
		<view class="seed-top">
			<view class="top-list" :class="selTop===idx&&'top-list-active'" v-for="(item,idx) in topList"
				:key="item.title" @click="selTopChange(idx)">{{item.title}}</view>
		</view>
		<view class="seed-main">
			<view class="page-list" v-for="item in pageList" :key="item.orderId" @click="jumpDetail(item)">
				<view class="list-top">
					<view class="list-time">下单时间：{{item.createTime}}</view>
				</view>
				<view class="list-mid" v-for="goods in item.goods" :key="goods.id" >
					<image class="goods-img" :src="goods.picture" mode="aspectFill"></image>
					<view style="flex-grow: 1;">
						<view class="goods-name">{{goods.goodsName}}</view>
						<view class="goods-info">
							<text class="goods-size">
								<text style="margin-right: 10rpx;">规格:{{goods.specificationName}}</text>
								数量:{{goods.quantity}}

							</text>
							<text class="goods-price">¥{{$toYuan(goods.discountsBackMoney)}}</text>

						</view>
					</view>
				</view>


				<view class="list-bottom" v-if="item.status===1">
					<view class="list-status c-primary">待付款</view>
					<view class="yuan-btn btn-success-hollow" @click.stop="clickCancel(item)">取消订单</view>
					<view class="yuan-btn btn-success" @click.stop="clickPay(item)">去付款</view>
				</view>
				<view class="list-bottom" v-else-if="item.status===2">
					<view class="list-status c-warning">待发货</view>
					<view class="yuan-btn btn-warning" @click.stop="clickAfterSales(item,1)">申请退货</view>
				</view>
				<view class="list-bottom" v-else-if="item.status===3">
					<view class="list-status c-primary">待收货</view>
					<view class="yuan-btn btn-success" @click.stop="clickGet(item)">确认收货</view>
					<view class="yuan-btn btn-warning" @click.stop="clickAfterSales(item,1)">申请退货</view>
				</view>
				<view class="list-bottom" v-else-if="item.status===4">
					<view class="list-status c-success">已完成</view>
					<view class="yuan-btn btn-warning" @click.stop="clickAfterSales(item,1)">申请退货</view>
				</view>
				<view class="list-bottom" v-else-if="item.status===5">
					<view class="list-status c-danger" v-if="item.refundApplyStatus===1">售后中：等待工作人员审核</view>
					<template v-else-if="item.refundApplyStatus===2">
						<view class="list-status c-danger">退还商品</view>
						<view class="yuan-btn btn-warning" @click.stop="clickAfterSales(item,2)">填写物流</view>
					</template>
					<template v-else-if="item.refundApplyStatus===3">
						<view class="list-status c-danger">售后申请被驳回</view>
						<view class="yuan-btn btn-success" @click.stop="clickGet(item)">确认收货</view>
					</template>

					<view class="list-status c-danger" v-else-if="item.refundApplyStatus===4">待退货</view>
					<view class="list-status c-warning" v-else-if="item.refundApplyStatus===5">等待物流退回</view>
					<view class="list-status c-success" v-else-if="item.refundApplyStatus===6">退款完成</view>
					<view class="list-status c-danger" v-else-if="item.refundApplyStatus===7">退款失败</view>

				</view>
				<view class="list-bottom" v-else-if="item.status===6">
					<view class="list-status c-danger">已取消</view>
				</view>
			</view>
			<view class="not-more" v-if="isLoading">加载中...</view>
			<view class="null-page" v-else-if="pageList.length<=0 ">
				<text class="iconfont">&#xe642;</text>
				<view class="null-page-tips">暂无数据~</view>
			</view>
			<view class="not-more" v-else-if="notMore">没有更多了...</view>
		</view>

		<view class="other-panel" :class="showOther&&'other-panel-show'">
			<view class="other-main" :class="showOther&&'other-main-show'">
				<view class="other-title">
					<text>售后信息</text>
					<text class="iconfont" @click="showOther=false">&#xe62c;</text>
				</view>
				<view class="yuan-form">
					<template v-if="otherType===1">
						<view class="yuan-form-row-list">
							<view class="yuan-form-label" style="margin-bottom: 20rpx;">退货理由：</view>
							<textarea class="yuan-textarea" v-model="afterSalesContent" placeholder="请输入退货理由"
								placeholder-class="placeholder-style">
								</textarea>
						</view>
						<view class="yuan-form-row-list">
							<view class="yuan-form-label" style="margin-bottom: 20rpx;">上传图片:</view>
							<view class="photo-panel">
								<template v-if="selHeadInfo.length>0">
									<view class="photo-img-box" v-for="(item,index) in selHeadInfo"
										:key="'photo_'+index">
										<view class="delete-img" @click="removePhoto(index)">移除</view>
										<image class="photo-img" :src="item" mode="aspectFit"
											@click="$lookImage(index,selHeadInfo)">
										</image>
									</view>
								</template>
								<view class="photo-img-box add-photo" @click="editPhoto"
									v-if="selHeadInfo.length<maxLen">
									<text class="iconfont">&#xe607;</text>
								</view>
							</view>
						</view>
					</template>


					<view class="yuan-form-row-list" v-else>
						<view class="yuan-form-label" style="margin-bottom: 20rpx;">物流信息：</view>
						<textarea class="yuan-textarea" v-model="afterSalesContent" placeholder="请输入物流公司+物流单号"
							placeholder-class="placeholder-style" />

					</view>
				</view>

				<view class="other-bottom">
					<view class="yuan-btn btn-default reset-btn" @click="cancelShowOther()">取消</view>
					<view class="yuan-btn btn-success sure-btn" @click="sureAfterSales">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, ref, reactive } from 'vue';
	import api from '@/common/api';
	import { chooseImage, doPay, hideLoading, showLoading, showToast, uploadFile } from '@/common/util';
	import { onPullDownRefresh, onReachBottom, onShow } from "@dcloudio/uni-app"
	import commonStore from '../../store/commonStore';
	const isLoading = ref(false)
	const topList = reactive([
		{ title: '全部', val: '' },
		{ title: '待付款', val: '1' },
		{ title: '待发货', val: '2' },
		{ title: '待收货', val: '3' },
		// { title: '已完成', val: '4' },
		{ title: '售后中', val: '5' },
	])
	const selTop = ref(0)
	const pageList = ref<any[]>([])
	const notMore = ref(true)
	onShow(async () => {
		if (commonStore.state.reload.indexOf('orderList') >= 0) {
			getPageList()
			commonStore.commit('delReload', 'orderList')
		}
	})

	onMounted(async () => {
		getPageList()
	})

	const pageSize = 10
	const pageNum = ref(1)
	const getPageList = async () => {
		showLoading()
		isLoading.value = true
		try {
			const res = await api.findUserOrderInfo({
				pageNum: pageNum.value,
				pageSize,
				status: topList[selTop.value].val
			})
			const data = res.data || { rows: [] }
			if (data.rows.length < pageSize) notMore.value = true
			pageList.value = pageList.value.concat(data.rows)
		} finally {
			isLoading.value = false
			hideLoading()
		}
	}
	const loadMore = () => {
		if (isLoading.value) return
		if (notMore.value) return
		pageNum.value = pageNum.value + 1
		getPageList()
	}
	const refreshList = () => {
		notMore.value = false
		pageNum.value = 1
		pageList.value = []
		getPageList()
	}
	onReachBottom(() => {
		//loadMore()
	})
	onPullDownRefresh(() => {
		refreshList()
		uni.stopPullDownRefresh()
	})
	const selTopChange = (idx) => {
		selTop.value = idx
		refreshList()
	}
	const clickGet = (item) => {
		uni.showModal({
			title: '提示',
			content: '你确定要确认收货吗？',
			confirmText: '确定',
			success: async (res) => {
				if (res.confirm) {
					showLoading()
					try {
						const res = await api.affirmProfile({
							id: item.orderId,
						})
						showToast('确认收货成功')
						commonStore.commit('addReload', 'index')
						refreshList()
					} finally {
						hideLoading()
					}
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const clickCancel = (item) => {
		uni.showModal({
			title: '提示',
			content: '你确定要取消该订单吗？',
			confirmText: '确定',
			success: async (res) => {
				if (res.confirm) {
					showLoading()
					try {
						const res = await api.cancelOrder({
							orderNo: item.orderNo,
						})
						showToast('取消成功')
						commonStore.commit('addReload', 'index')
						refreshList()
					} finally {
						hideLoading()
					}
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const jumpDetail = (item) => {
		uni.navigateTo({ url: '/pages/user/orderDetail?id=' + item.orderId + '&createTime=' + item.createTime })

	}
	const jumpGoods=(goods)=>{
		uni.navigateTo({ url: '/pages/category/goodsDetail?id=' + goods.goodsId })
	}
	const clickPay = async (payInfo) => {
		doPay(payInfo, () => {
			refreshList()
		}, () => {
			refreshList()
		})
	}

	const showOther = ref(false)
	const otherType = ref(1)
	const afterSalesContent = ref('')
	let refundItem : any = {}
	const clickAfterSales = (item, type) => {
		refundItem = item
		afterSalesContent.value=''
		selHeadInfo.value=[]
		otherType.value = type
		showOther.value = true
	}
	const cancelShowOther = () => {
		showOther.value = false
	}
	const doSave = async (imgArr) => {
		try {
			const res = await api.applyRefund({
				orderId: refundItem.orderId,
				refundReason: afterSalesContent.value,
				refundImages: imgArr
			})
			showToast('申请成功')
			showOther.value = false
			refreshList()
		} finally {
			hideLoading()
		}
	}
	const sureAfterSales = async () => {
		if (otherType.value === 1) {
			if (afterSalesContent.value === '') {
				showToast('请输入退货理由')
				return
			}
			showLoading()
			let num = 0
			let total = selHeadInfo.value.length
			const imgArr = []
			if(total>0){
				for (let i = 0; i < total; i++) {
					const item = selHeadInfo.value[i]
					uploadFile(item).then((res : any) => {
						const data=JSON.parse(res.data)
						imgArr.push(data.msg)
						num++
						if (num >= total) doSave(imgArr)
					})
				}
			}else{
				doSave(imgArr)
			}
			
		}else{
			if (afterSalesContent.value === '') {
				showToast('请输入物流信息')
				return
			}
			showLoading()
			
			const res = await api.fillReturnLogistics({
				orderId: refundItem.orderId,
				returnTrackingNumber: afterSalesContent.value,
				returnLogisticsCompany: ''
			})
			hideLoading()
			showToast('填写成功')
			showOther.value = false
			refreshList()
		}

	}


	const maxLen = ref(6)
	const selHeadInfo = ref([])
	const editPhoto = () => {
		if (selHeadInfo.value.length >= maxLen.value) {
			uni.showToast({
				title: `最多只能上传${maxLen.value}张图片`,
				duration: 2000
			});
			return
		}
		chooseImage((res) => {
			selHeadInfo.value.push(res.tempFilePaths[0] + '')
		})
	}
	const removePhoto = (idx : number) => {
		selHeadInfo.value.splice(idx, 1)
	}
</script>

<style lang="scss">
	.user-mysponsor {
		.seed-top {
			background-color: #fff;
		}

		.top-list {
			width: 20%;
			display: inline-block;
			border-bottom: solid 6rpx #fff;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 30rpx;
			color: #5B5B5B;
		}

		.top-list-active {
			font-weight: bold;
			color: #17CC77;
			border-bottom: solid 6rpx #17CC77;
		}

		.seed-main {
			padding: 20rpx;
		}

		.page-list {
			background-color: #fff;
			box-shadow: 0 8rpx 10rpx 0 rgba(0, 0, 0, 0.1);
			border-radius: 10rpx;
			margin-bottom: 20rpx;
			padding: 20rpx;

		}

		.list-time {
			color: #666;
			font-size: 28rpx;
			text-align: right;
		}

		.list-mid {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: solid 1px #f6f6f6;
		}

		.goods-img {
			width: 100rpx;
			height: 100rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
			flex-shrink: 0;
		}

		.goods-name {
			font-size: 30rpx;
			color: #333;
		}

		.goods-info {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 10rpx;
		}

		.goods-price {
			color: #FF315A;
			font-size: 42rpx;
			font-weight: bold;
		}

		.goods-size {
			font-size: 26rpx;
			color: #666;
		}


		.list-bottom {
			padding-top: 15rpx;
			display: flex;
			align-items: center;
			margin-top: 5rpx;

			.yuan-btn {
				width: 150rpx;
				height: 60rpx;
				border-radius: 60rpx;
				margin-left: 10rpx;
			}
		}

		.list-status {
			flex-grow: 1;
			font-size: 30rpx;
		}


		.other-panel {
			position: fixed;
			background-color: rgba(0, 0, 0, 0.3);
			width: 100%;
			height: 100%;
			left: 0;
			top: 0;
			transform: translateY(100%);
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.other-panel-show {
			transform: translateY(0);
		}

		.other-main {
			background-color: #fff;
			border-radius: 10rpx;
			width: 90%;
			padding: 0 20rpx 50rpx 20rpx;
			transform: translateY(100%);
			transition: all 0.3s;
		}

		.other-main-show {
			transform: translateY(0);
		}

		.other-title {
			color: #333;
			font-size: 32rpx;
			text-align: center;
			position: relative;
			line-height: 80rpx;
			font-weight: bold;

			.iconfont {
				position: absolute;
				right: 0;
				top: 0;
				font-size: 32rpx;
				padding: 5rpx;
				font-weight: lighter;
			}
		}

		.other-bottom {
			display: flex;
			align-items: center;
			margin-top: 50rpx;
			justify-content: center;

			.reset-btn {
				width: 220rpx;
				height: 70rpx;
				margin-right: 50rpx;
				border-radius: 70rpx;
			}

			.sure-btn {
				width: 200rpx;
				height: 70rpx;
				border-radius: 70rpx;
			}
		}

		.photo-panel {
			display: flex;
			flex-wrap: wrap;
		}

		.photo-img-box {
			margin-right: 10rpx;
			margin-bottom: 15rpx;
			background-color: #F7F8FA;
			height: 200rpx;
			border-radius: 10rpx;
			width: 200rpx;
			position: relative;
		}

		.photo-img-box:nth-child(3n) {
			margin-right: 0;
		}

		.add-photo {
			line-height: 200rpx;
			text-align: center;

			.iconfont {
				font-size: 50rpx;
				color: #D6D7D7;
			}
		}

		.photo-img {
			width: 100%;
			height: 100%;
		}

		.delete-img {
			position: absolute;
			top: 0;
			right: 0;
			background-color: rgba(0, 0, 0, 0.5);
			font-size: 22rpx;
			padding: 2rpx 10rpx;
			color: #fff;
			border-radius: 4rpx;
			z-index: 10;
		}
	}
</style>